package com.atguigu.gulimall.cart.Web;

import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class CartWeb {

    @Autowired
    private CartService cartService;

    /**
     * 添加购物车
     * @param skuId
     * @param num
     * @param model
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/addToCart.html")
    public String addCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes ra) throws ExecutionException, InterruptedException {
         cartService.addToCart(skuId,num);
         ra.addAttribute("skuId",skuId);
        return "redirect:http://cart.gulimall.com/addCartRedirect.html";
    }

    /**
     * 添加购物车后重定向的页面
     */
    @GetMapping("/addCartRedirect.html")
    public String addCartRediract(@RequestParam("skuId") Long skuId,Model model){
        //获取购物车中的商品数量
        CartItemVo itemVo = cartService.getCartNum(skuId);
        model.addAttribute("item",itemVo);
        return "success";

    }


    /**
     * 删除购物项
     */
    @GetMapping("/deleteItem")
    public String delete(@RequestParam("skuId")Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:cartList.html";
    }

    /**
     * 购物车列表
     */
    @GetMapping("/cart.html")
    public String cartList(Model model){
        try {
            CartVo vo =  cartService.getCartList();
            model.addAttribute("cart",vo);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "cartList";
    }

    /**
     * 修改购物项信息
     */
    @GetMapping("/cartItem")
    public String cartItem(@RequestParam("skuId")Integer skuId,
                            @RequestParam("check")Integer check){

        cartService.UpdateCartItem(skuId,check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }


}
